package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.DetectionCycle;
import com.ruoyi.system.domain.Ptesting;
import com.ruoyi.system.domain.vo.PtestingVo;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.IPersonService;
import com.ruoyi.system.service.IPtestingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 核酸信息Controller
 *
 * @author ruoyi
 * @date 2022-04-16
 */
@RestController
@RequestMapping("/system/ptesting")
public class PtestingController extends BaseController {
    @Autowired
    private IPtestingService ptestingService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private IPersonService personService;


    /**
     * 查询核酸信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:ptesting:list')")
    @GetMapping("/list")
    public TableDataInfo list(Ptesting ptesting) throws ParseException {
        List<Map> list1 = new ArrayList<>();
        if (ptesting.getState() == 2) {
            //返回时间集合
            List<Map> list4 = new ArrayList<>();
            List<String> dates = DateUtils.findDates(ptesting.getStarTime(), ptesting.getEntTime());
            List<Ptesting> list2 = new ArrayList<>();
            for (int a = 0; a < dates.size(); a++) {
                //查询全部的人
                ptesting.setState(null);
                list4 = ptestingService.selectNotPtestionZONG(ptesting);
                //未检测的人员
                String s = dates.get(a);//
                ptesting.setStarTime(s + " 00:00:00");
                ptesting.setEntTime(s + " 23:59:59");
                ptesting.setState(2L);
                list1 = ptestingService.selectNotPtestionNo(ptesting);
                for (int c = 0; c < list1.size(); c++) {
                    Map map = list1.get(c);
                    Ptesting ptesting1 = new Ptesting();
                    DetectionCycle detectionCycle = new DetectionCycle();
                    List detectionCyclelist = new ArrayList();
                    //部门
                    ptesting1.setDeptId(Long.valueOf(map.get("dept_id") + ""));
                    //类别
                    detectionCycle.setCategoryName(map.get("category_name") + "");
                    detectionCyclelist.add(detectionCycle);
                    ptesting1.setDetectionCycleList(detectionCyclelist);
                    //姓名
                    ptesting1.setPersonName(map.get("person_name") + "");
                    //手机号
                    ptesting1.setPhoneNumber(null);
                    if (StringUtils.isNotNull(map.get("phone_number"))) {
                        ptesting1.setPhoneNumber(Long.valueOf(map.get("phone_number") + ""));
                    }
                    //身份证号
                    ptesting1.setCardId(map.get("card_id") + "");
                    //检测时间
                    ptesting1.setDetectionTime(DateUtils.parseDate(s));
                    //状态
                    ptesting1.setState(2L);
                    list2.add(ptesting1);
                }
            }
            //获取分页
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();//页数
            Integer pageSize = pageDomain.getPageSize();//条数
            List<Ptesting> list3 = new ArrayList<>();
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                int i = (pageNum * pageSize) - pageSize; //开始取值
                if (list2.size() > pageNum * pageSize) {
                    int i1 = pageNum * pageSize;
                    for (int q = i; q < i1; q++) {
                        Ptesting ptesting1 = list2.get(q);
                        ptesting1.setDeptName(gitDept(ptesting1.getDeptId()));
                        list3.add(ptesting1);
                    }
                } else {
                    for (int q = i; q < list2.size(); q++) {
                        Ptesting ptesting1 = list2.get(q);
                        ptesting1.setDeptName(gitDept(ptesting1.getDeptId()));
                        list3.add(ptesting1);
                    }
                }
            }
            return getDataTableNot(list3, Long.valueOf(list2.size() + ""), list4.size());
        }
        if (StringUtils.isNotEmpty(ptesting.getStarTime()) && StringUtils.isNotEmpty(ptesting.getEntTime())) {
            ptesting.setStarTime(ptesting.getStarTime() + " 00:00:00");
            ptesting.setEntTime(ptesting.getEntTime() + " 23:59:59");
        }
        startPage();
        List<Ptesting> list = ptestingService.selectPtestingList(ptesting);
        return getDataTable(list);
    }

    public String gitDept(Long dept) {
        String deptName = "";
        String[] split = ((sysDeptMapper.selectDeptById(dept).getAncestors()) + "," + dept).split(",");
        for (int a = 1; a < split.length; a++) {
            deptName += sysDeptMapper.selectDeptById(Long.valueOf(split[a])).getDeptName() + "-";
        }
        return deptName.substring(0, deptName.length() - 1);
    }

    /**
     * 导出核酸信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:ptesting:export')")
    @Log(title = "核酸信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Ptesting ptesting) {
        List<Ptesting> list = ptestingService.selectPtestingList(ptesting);
        ExcelUtil<Ptesting> util = new ExcelUtil<Ptesting>(Ptesting.class);
        util.exportExcel(response, list, "核酸信息数据");
    }

    /**
     * 获取核酸信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:ptesting:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ptestingService.selectPtestingById(id));
    }

    /**
     * 新增核酸信息
     */
    @PreAuthorize("@ss.hasPermi('system:ptesting:add')")
    @Log(title = "核酸信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Ptesting ptesting) {
        return toAjax(ptestingService.insertPtesting(ptesting));
    }

    /**
     * 修改核酸信息
     */
    @PreAuthorize("@ss.hasPermi('system:pte sting:edit')")
    @Log(title = "核酸信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Ptesting ptesting) {
        return toAjax(ptestingService.updatePtesting(ptesting));
    }

    /**
     * 删除核酸信息
     */
    @PreAuthorize("@ss.hasPermi('system:ptesting:remove')")
    @Log(title = "核酸信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ptestingService.deletePtestingByIds(ids));
    }


    /**
     * 疫情防控信息导入模板下载
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:ptesting:import')")
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<PtestingVo> util = new ExcelUtil<PtestingVo>(PtestingVo.class);
        return util.importTemplateExcel("防控信息");
    }

    /**
     * 导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "疫情管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<PtestingVo> util = new ExcelUtil<PtestingVo>(PtestingVo.class);
        List<PtestingVo> personList = util.importExcel(file.getInputStream());
        String message = ptestingService.imporPerson(personList, updateSupport);
        return AjaxResult.success(message);
    }


}
